﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BL.Abstract;
using NHibernate;
using NHibernate.Cfg;
using CommonHelper;

namespace BL.Managers
{
    public class RepositoryFactory : IRepositoryFactory
    {
        #region Fields

        public const string SYSTEM_CONFIG_NAME = "system";

        private readonly string _configFileName;
        private readonly string _connectionString;
        private ISession _session;

        #endregion

        #region Constructors

        public RepositoryFactory()
        {
            _configFileName = Common.CreateConfigFileName(SYSTEM_CONFIG_NAME);
            _session = CreateSession();
        }

        public RepositoryFactory(string connectionString)
        {
            _configFileName = Common.CreateConfigFileName(SYSTEM_CONFIG_NAME);
            _connectionString = connectionString;
            _session = CreateSession();
        }

        #endregion

        #region IRepositoryFactory Members

        public IDBManager<T> Get<T>() where T : class
        {
            return new DBManager<T>(_session);
        }

        public void Clear()
        {
            _session.Clear();
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            _session.Close();
            _session.Dispose();
        }

        #endregion

        #region Helpers

        private ISession CreateSession()
        {
            ISessionFactory sessionFactory = CreateSessionFactory();
            if (sessionFactory == null)
            {
                sessionFactory = CreateSessionFactory();
            }
            return sessionFactory.OpenSession();
        }

        private ISessionFactory CreateSessionFactory()
        {
            Configuration configuration = new Configuration();
            configuration.Configure(_configFileName);
            if (!string.IsNullOrEmpty(_connectionString))
            {
                configuration.SetProperty("connection.connection_string", _connectionString);
            }
            return configuration.BuildSessionFactory();

        }

        #endregion
    }
}
